package com.wanwanbookstore.servlet;

import com.wanwanbookstore.dao.CartDAO;
import com.wanwanbookstore.dao.BookDAO;
import com.wanwanbookstore.entity.CartItem;
import com.wanwanbookstore.entity.User;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class CartServlet extends HttpServlet {
    private CartDAO cartDAO = new CartDAO();
    private BookDAO bookDAO = new BookDAO();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 首先检查是否有action参数，如果有则交给doPost处理，支持GET方式的删除操作
        String action = request.getParameter("action");
        if (action != null) {
            // 对于有action参数的GET请求，调用doPost方法处理
            doPost(request, response);
            return;
        }

        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            // 设置响应内容类型为HTML
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().println("<!DOCTYPE html>");
            response.getWriter().println("<html>");
            response.getWriter().println("<head>");
            response.getWriter().println("<meta charset=\"UTF-8\">");
            response.getWriter().println("<title>提示</title>");
            response.getWriter().println("</head>");
            response.getWriter().println("<body>");
            response.getWriter().println("<script type=\"text/javascript\">");
            response.getWriter().println("alert('请先登录！');");
            response.getWriter().println("window.location.href = 'login.jsp';");
            response.getWriter().println("</script>");
            response.getWriter().println("</body>");
            response.getWriter().println("</html>");
            return;
        }

        // 检查购物车中是否有已下架的商品
        List<CartItem> deletedItems = cartDAO.checkDeletedBooks(user.getId());
        if (!deletedItems.isEmpty()) {
            request.setAttribute("deletedItems", deletedItems);
            // 可以选择自动删除这些商品
        }

        // 获取购物车列表
        List<CartItem> cartItems = cartDAO.getCartByUserId(user.getId());
        request.setAttribute("cartItems", cartItems);

        // 计算总价
        double totalPrice = 0;
        for (CartItem item : cartItems) {
            if (item.getBook() != null && !item.getBook().isDeleted()) {
                totalPrice += item.getTotalPrice();
            }
        }
        request.setAttribute("totalPrice", totalPrice);

        request.getRequestDispatcher("cart.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            response.sendRedirect("login.jsp");
            return;
        }

        String action = request.getParameter("action");
        if (action != null) {
            switch (action) {
                case "add":
                case "addToCart":
                    addToCart(request, response, user);
                    break;
                case "update":
                    updateCart(request, response, user);
                    break;
                case "delete":
                    deleteCartItem(request, response, user);
                    break;
                case "clear":
                    clearCart(request, response, user);
                    break;
                default:
                    // 对于未知操作，显示提示并返回首页
                    response.setContentType("text/html;charset=UTF-8");
                    response.getWriter().println("<!DOCTYPE html>");
                    response.getWriter().println("<html>");
                    response.getWriter().println("<head>");
                    response.getWriter().println("<meta charset=\"UTF-8\">");
                    response.getWriter().println("<title>提示</title>");
                    response.getWriter().println("</head>");
                    response.getWriter().println("<body>");
                    response.getWriter().println("<script type=\"text/javascript\">");
                    response.getWriter().println("alert('未知操作！');");
                    response.getWriter().println("window.location.href = 'cart';");
                    response.getWriter().println("</script>");
                    response.getWriter().println("</body>");
                    response.getWriter().println("</html>");
            }
        } else {
            // 默认显示购物车页面改为直接转发到cart.jsp
            List<CartItem> cartItems = cartDAO.getCartByUserId(user.getId());
            double totalPrice = 0;
            for (CartItem item : cartItems) {
                if (item.getBook() != null && !item.getBook().isDeleted()) {
                    totalPrice += item.getTotalPrice();
                }
            }

            request.setAttribute("cartItems", cartItems);
            request.setAttribute("totalPrice", totalPrice);
            request.getRequestDispatcher("cart.jsp").forward(request, response);
        }
    }

    private void addToCart(HttpServletRequest request, HttpServletResponse response, User user) throws IOException {
        int bookId = Integer.parseInt(request.getParameter("bookId"));
        int quantity = 1;
        if (request.getParameter("quantity") != null) {
            quantity = Integer.parseInt(request.getParameter("quantity"));
        }
        String type = request.getParameter("type"); // 获取购买类型

        // 设置响应内容类型为HTML
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().println("<!DOCTYPE html>");
        response.getWriter().println("<html>");
        response.getWriter().println("<head>");
        response.getWriter().println("<meta charset=\"UTF-8\">");
        response.getWriter().println("<title>提示</title>");
        response.getWriter().println("</head>");
        response.getWriter().println("<body>");
        response.getWriter().println("<script type=\"text/javascript\">");

        // 检查图书是否存在且未下架
        com.wanwanbookstore.entity.Book book = bookDAO.getBookById(bookId);
        if (book != null && !book.isDeleted() && book.getStock() >= quantity) {
            if ("direct".equals(type)) {
                // 立即购买逻辑：不加入购物车数据库，而是将商品信息存储在session中
                HttpSession session = request.getSession();
                // 创建一个临时的购买项
                CartItem directBuyItem = new CartItem();
                directBuyItem.setBookId(bookId);
                directBuyItem.setQuantity(quantity);
                directBuyItem.setBook(book);
                
                // 将直接购买的商品信息存储在session中
                session.setAttribute("directBuyItem", directBuyItem);
                // 清除可能存在的购物车结算模式标志
                session.removeAttribute("useCartForCheckout");
                
                response.getWriter().println("window.location.href = 'checkout';");
            } else {
                // 正常加入购物车逻辑
                if (cartDAO.addToCart(user.getId(), bookId, quantity)) {
                    response.getWriter().println("alert('添加成功！');");
                    // 使用history.back()保持页面滚动位置
                    response.getWriter().println("window.history.back();");
                } else {
                    response.getWriter().println("alert('添加失败！');");
                    // 使用history.back()保持页面滚动位置
                    response.getWriter().println("window.history.back();");
                }
            }
        } else {
            // 显示图书不存在或库存不足弹窗
            response.getWriter().println("alert('图书不存在或库存不足！');");
            // 使用history.back()保持页面滚动位置
            response.getWriter().println("window.history.back();");
        }

        response.getWriter().println("</script>");
        response.getWriter().println("</body>");
        response.getWriter().println("</html>");
    }

    private void updateCart(HttpServletRequest request, HttpServletResponse response, User user) throws IOException {
        int itemId = Integer.parseInt(request.getParameter("itemId"));
        int quantity = Integer.parseInt(request.getParameter("quantity"));

        // 设置响应内容类型为HTML
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().println("<!DOCTYPE html>");
        response.getWriter().println("<html>");
        response.getWriter().println("<head>");
        response.getWriter().println("<meta charset=\"UTF-8\">");
        response.getWriter().println("<title>提示</title>");
        response.getWriter().println("</head>");
        response.getWriter().println("<body>");
        response.getWriter().println("<script type=\"text/javascript\">");

        boolean success = false;
        if (quantity > 0) {
            success = cartDAO.updateCartItem(itemId, quantity);
        } else {
            success = cartDAO.deleteCartItem(itemId);
        }

        if (success) {
            response.getWriter().println("alert('更新成功！');");
        } else {
            response.getWriter().println("alert('更新失败！');");
        }
        response.getWriter().println("window.location.href = 'cart';");
        response.getWriter().println("</script>");
        response.getWriter().println("</body>");
        response.getWriter().println("</html>");
    }

    private void deleteCartItem(HttpServletRequest request, HttpServletResponse response, User user) throws IOException {
        String itemIdStr = request.getParameter("itemId");

        // 添加调试日志
        System.out.println("收到删除请求，itemId参数: " + itemIdStr);
        System.out.println("参数类型: " + (itemIdStr != null ? itemIdStr.getClass().getName() : "null"));

        // 设置响应内容类型为HTML
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().println("<!DOCTYPE html>");
        response.getWriter().println("<html>");
        response.getWriter().println("<head>");
        response.getWriter().println("<meta charset=\"UTF-8\">");
        response.getWriter().println("<title>提示</title>");
        response.getWriter().println("</head>");
        response.getWriter().println("<body>");
        response.getWriter().println("<script type=\"text/javascript\">");

        // 检查itemId是否为空或无效
        if (itemIdStr == null || itemIdStr.trim().isEmpty()) {
            System.out.println("错误: itemId参数为空或无效");
            response.getWriter().println("alert('参数错误，无法删除商品！');");
        } else {
            try {
                int itemId = Integer.parseInt(itemIdStr);
                System.out.println("成功转换为整数: " + itemId);
                boolean success = cartDAO.deleteCartItem(itemId);
                System.out.println("删除操作结果: " + success);
                if (success) {
                    response.getWriter().println("alert('删除成功！');");
                } else {
                    response.getWriter().println("alert('删除失败！');");
                }
            } catch (NumberFormatException e) {
                System.out.println("错误: 无法将itemId转换为整数，原始值: '" + itemIdStr + "'");
                response.getWriter().println("alert('参数格式错误，无法删除商品！');");
            }
        }
        response.getWriter().println("window.location.href = 'cart';");
        response.getWriter().println("</script>");
        response.getWriter().println("</body>");
        response.getWriter().println("</html>");
    }

    private void clearCart(HttpServletRequest request, HttpServletResponse response, User user) throws IOException {
        // 设置响应内容类型为HTML
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().println("<!DOCTYPE html>");
        response.getWriter().println("<html>");
        response.getWriter().println("<head>");
        response.getWriter().println("<meta charset=\"UTF-8\">");
        response.getWriter().println("<title>提示</title>");
        response.getWriter().println("</head>");
        response.getWriter().println("<body>");
        response.getWriter().println("<script type=\"text/javascript\">");

        boolean success = cartDAO.clearCart(user.getId());
        if (success) {
            response.getWriter().println("alert('清空成功！');");
        } else {
            response.getWriter().println("alert('清空失败！');");
        }
        response.getWriter().println("window.location.href = 'cart';");
        response.getWriter().println("</script>");
        response.getWriter().println("</body>");
        response.getWriter().println("</html>");
    }
}